import React, { Component } from 'react';
import { Modal, Form, message, Row, Col, Input, Card, Tree, Select } from 'antd';

const FormItem = Form.Item;
const { TreeNode } = Tree;
const { Option } = Select;
export default class SetParams extends Component {
  state = {
    devIdArray: this.props.selectedRows,
  };
  onCheck = checkedKeys => {
    this.setState({ devIdArray: checkedKeys });
  };
  handleSet = () => {
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const { dispatch } = this.props;
        const { serverAddr, realTimeSrvAddr, companyId } = values;
        //const devIds = selectedRows.join(',');
        const devIds = this.state.devIdArray.join(',');
        dispatch({
          type: 'dev/setIpAddress',
          payload: { devIds, serverAddr, realTimeSrvAddr, companyId },
          callback: () => {
            message.success('设置通信地址成功.');
          },
        });
        this.props.handleModalVisible(false);
      }
    });
  };

  render() {
    const { modalVisible, form, handleModalVisible, selectedRows, company } = this.props;
    return (
      <Modal
        title="设置通信参数"
        visible={modalVisible}
        onOk={this.handleSet}
        onCancel={() => handleModalVisible(false)}
      >
        <Form layout="vertical">
          <FormItem label="公司：">
            {form.getFieldDecorator('companyId')(
              <Select allowClear="true" placeholder="请选择" style={{ width: '100%' }}>
                {company.map(item => (
                  <Option value={item.code}>{item.name}</Option>
                ))}
              </Select>
            )}
          </FormItem>
          <FormItem label="服务器地址(IP:端口)或域名：">
            {form.getFieldDecorator('serverAddr', {
              rules: [{ required: true, message: '服务器地址(IP:端口)或域名：...' }],
            })(<Input />)}
          </FormItem>
          <FormItem label="RealTime服务器地址(IP:端口)或域名：">
            {form.getFieldDecorator('realTimeSrvAddr', {
              rules: [{ required: true, message: 'RealTime服务器地址(IP:端口)或域名：...' }],
            })(<Input />)}
          </FormItem>
        </Form>
        <Row style={{ width: '100%' }}>
          <Card title="设备列表（多选）" bodyStyle={{ height: 600, overflow: 'scroll' }}>
            {selectedRows.length ? (
              <Tree
                checkable
                style={{ height: 600 }}
                defaultCheckedKeys={selectedRows}
                onCheck={this.onCheck}
              >
                {selectedRows.map(data => (
                  <TreeNode title={data} key={data} />
                ))}
              </Tree>
            ) : (
              'loading tree'
            )}
          </Card>
        </Row>
      </Modal>
    );
  }
}
